package com.stars.sun.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by 340082 on 2018/1/30.
 */
public class FileUtils {
    public static List<File> findFiles(String path ,final String... fileExtension) {
        List<File> files = new LinkedList<File>();
        try {
            URL url = FileUtils.class.getResource(path);
            if (url == null)
                return files;
            String protocol = url.getProtocol();
            if(fileExtension.length == 0){
                return files;
            }
            if ("file".equals(protocol)) {// 如果是以文件的形式保存在服务器上
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");// 获取包的物理路径
                File dir = new File(filePath);
                if (!dir.exists() || !dir.isDirectory())
                    return files;
                File[] targetFiles = dir.listFiles(new FileFilter() {
                    public boolean accept(File file) {
                        for (int i = 0 ; i < fileExtension.length ; i++){
                            if(file.getName().endsWith(fileExtension[i]))
                            return true;
                        }
                        return false;
                    }
                });
                if (targetFiles != null && targetFiles.length > 0) {
                    files.addAll(Arrays.asList(targetFiles));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files;
    }
}
